package com.magenta.maxoptra.gis.service;

import com.magenta.maxoptra.gis.AddressesCacheMBean;
import com.magenta.maxoptra.gis.RoutesCacheMBean;
import org.jboss.mx.util.MBeanServerLocator;

import javax.management.ObjectName;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Project: Santa-cruz
 * Author:  Irina Isaeva
 * Created: 14.06.12 14:07
 * <p/>
 * Copyright (c) 1999-2012 Magenta Corporation Ltd. All Rights Reserved.
 * Magenta Technology proprietary and confidential.
 * Use is subject to license terms.
 * <p/>
 * $Id$
 */
public class ServiceLocator {

    private static ServiceLocator instance;
    private Map<Class, Object> proxies;

    public static ServiceLocator getInstance() {
        if (instance == null) {
            instance = new ServiceLocator();

        }
        return instance;
    }

    private ServiceLocator() {
        proxies = new ConcurrentHashMap<Class, Object>();
    }

    public static <T> T lookupJMX(Class<T> clazz, String name) {
        final Map<Class, Object> map = getInstance().proxies;
        T proxy = (T) map.get(clazz);
        if (proxy == null) {
            try {
                proxy = TypeSafeMBeanProxy.newMBeanProxy(MBeanServerLocator.locate(), new ObjectName(name), clazz);
                map.put(clazz, proxy);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return proxy;
    }

    public static RoutesCacheMBean getRoutesCacheMBean(){
        return ServiceLocator.lookupJMX(RoutesCacheMBean.class, RoutesCacheMBean.OBJECT_NAME);
    }

    public static AddressesCacheMBean getAddressesCacheMBean(){
        return ServiceLocator.lookupJMX(AddressesCacheMBean.class, AddressesCacheMBean.OBJECT_NAME);
    }
}
